package com.base.cn.platform.os.service.user.account;

import com.base.cn.platform.os.common.msg.WXTmpEnum;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.account.CusUserCashRecordDao;
import com.base.cn.platform.os.entity.manage.user.SysUser;
import com.base.cn.platform.os.entity.user.account.CusUserAccount;
import com.base.cn.platform.os.entity.user.account.CusUserCashRecord;
import com.base.cn.platform.os.entity.user.account.CusUserCashRecordCondition;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.manage.user.SysUserBiz;
import com.base.cn.platform.os.service.op.affiche.tmp.SendMessage;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户提现记录Biz
 *
 * @author s.li
 * @date 2018/12/01
 */
@Service
public class CusUserCashRecordBiz extends BaseBiz<CusUserCashRecord, CusUserCashRecordDao> {

    @Autowired
    private CusUserAccountBiz cusUserAccountBiz;
    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private SysUserBiz sysUserBiz;
    @Autowired
    private SendMessage sendMessage;

    /**
     * 审核提现记录
     * @param cashRecord 记录对象
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void auditPass(CusUserCashRecord cashRecord) {
        if(cashRecord.getStatus().intValue()==3){//驳回
            cusUserAccountBiz.userAccountRefundCash(cashRecord.getUserId(),cashRecord.getExamineUserId(),cashRecord.getPrice());
        }
        this.updateById(cashRecord,null);
        //发送消息通知
        Map<BigDecimal,List> dataListMap = new HashMap<>();
        dataListMap.put(cashRecord.getUserId(),Arrays.asList(cashRecord));
        sendMessage.sendMessage(WXTmpEnum.CASH, Arrays.asList(cashRecord.getUserId()),dataListMap);
    }

    /**
     * 保存用户提现记录
     * @param userAccount 用户账户对象
     * @param userCashRecord 提现记录对象
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void createUserCashRecord(CusUserAccount userAccount,CusUserCashRecord userCashRecord) throws Exception{
        //扣除用户金额
        cusUserAccountBiz.userAccountCash(userAccount,userCashRecord.getPrice());
        userCashRecord.setStatus(1);
        this.save(userCashRecord);
    }

    /**
     * 分成查询用户提现记录列表
     * @param condition 查询条件
     * @param page 页码条件
     * @return PageInfo<CusUserCashRecord>
     */
    public PageInfo<CusUserCashRecord> findUserCashRecordListPage(CusUserCashRecordCondition condition,
                                                                  Pagination page) {
        if(StringUtils.isNotEmpty(condition.getKeyWord())){
            UserCondition userCondition = new UserCondition();
            userCondition.setKeyWord(condition.getKeyWord());
            List<CusUser> userList = cusUserBiz.queryUserList(userCondition,null,null,false,false,false,false,false,false,false);
            if(ObjectUtils.isEmpty(userList)){
                return new PageInfo<>();
            }
            String userIds = userList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
            condition.setUserIds(userIds);
            condition.setUserList(userList);
        }
        String whereSql = this.getWhereSql(condition);
        PageInfo<CusUserCashRecord> pageInfo = this.findPage(whereSql,page,null);
        this.setCashRecordExtensionData(pageInfo.getList(),condition);
        return pageInfo;
    }

    //=====================================================================================================

    /**
     * 设置提现记录扩展数据
     * @param userCashRecordList 提现记录列表
     * @param condition 条件对象
     */
    private void setCashRecordExtensionData(List<CusUserCashRecord> userCashRecordList ,
                                            CusUserCashRecordCondition condition){
        if(ObjectUtils.isNotEmpty(userCashRecordList) && ObjectUtils.isNotEmpty(condition)){
            if(condition.isUserData()){
                if(ObjectUtils.isNotEmpty(condition.getUserList())){
                    userCashRecordList.forEach(e->{
                        Map<BigDecimal,CusUser> userMap = condition.getUserList().stream().collect(Collectors.toMap(user->user.getId(),user->user));
                        e.setUser(userMap.get(e.getUserId()));
                    });
                }else{
                    cusUserBiz.setUserData(userCashRecordList,true);
                }
            }
            if(condition.isExamineUserData()){
                String examineUserIds = userCashRecordList.stream().filter(e->DataUtil.idIsNotNull(e.getExamineUserId())).map(e->e.getExamineUserId().toString()).collect(Collectors.joining(","));
                if(StringUtils.isNotEmpty(examineUserIds)){
                    Map<BigDecimal, SysUser> sysUserMap = sysUserBiz.findSysUserByIds(examineUserIds);
                    if(ObjectUtils.isNotEmpty(sysUserMap)) {
                        userCashRecordList.forEach(e->{
                            e.setExamineUser(sysUserMap.get(e.getExamineUserId()));
                        });
                    }
                }
            }
        }
    }


    /**
     * 获取查询条件SQL
     * @param condition
     * @return
     */
    private String getWhereSql(CusUserCashRecordCondition condition){
        StringBuilder whereSql = new StringBuilder(" 1=1");
        if(ObjectUtils.isNotEmpty(condition)){
            if(DataUtil.idIsNotNull(condition.getUserId())){
                whereSql.append(" and userId = ").append(condition.getUserId());
            }
            if(ObjectUtils.isNotEmpty(condition.getStatus()) && condition.getStatus().intValue() > 0){
                whereSql.append(" and status = ").append(condition.getStatus());
            }
            if(StringUtils.isNotEmpty(condition.getSourceForm())){
                whereSql.append(" and sourceForm ='").append(condition.getSourceForm()).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getBeginTime())){
                whereSql.append(" and createTime >= ").append("'").append(DateUtils.format(condition.getBeginTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(ObjectUtils.isNotEmpty(condition.getEndTime())){
                whereSql.append(" and createTime <= ").append("'").append(DateUtils.format(condition.getEndTime(),"yyyy-MM-dd HH:mm:ss")).append("'");
            }
            if(StringUtils.isNotEmpty(condition.getYear())){
                whereSql.append(" and DATE_FORMAT(createTime,'%Y') = ").append(condition.getYear());
            }
            if(StringUtils.isNotEmpty(condition.getUserIds())){
                whereSql.append(" and userId in (").append(condition.getUserIds()).append(")");
            }
        }
        whereSql.append(" order by createTime desc");
        return whereSql.toString();
    }
}
